package com.lu.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lu.common.utils.Constants;
import com.lu.common.utils.JwtUtil;
import com.lu.common.vo.UserInfoVo;
import com.lu.sys.controller.dto.UserPasswordDTO;
import com.lu.sys.entity.Menu;
import com.lu.sys.entity.User;
import com.lu.sys.entity.UserRole;
import com.lu.sys.mapper.UserMapper;
import com.lu.sys.mapper.UserRoleMapper;
import com.lu.sys.service.IMenuService;
import com.lu.sys.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.sys.service.impl.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lulu
 * @since 2023-04-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private  UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Autowired
    private IMenuService menuService;

    @Override
    public Map<String, Object> login(User user) {
        //根据用户名和密码查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
//        wrapper.eq(User::getPassword,user.getPassword());
        User loginUser = this.baseMapper.selectOne(wrapper);
        //结果不为空，并且密码和传入的密码匹配，则生成一个token,并将用户信息存入redis
        if (loginUser != null && passwordEncoder.matches(user.getPassword(), loginUser.getPassword())) {//match里面的参数，前面是输入的密码，后面是数据库里转码的密码
            //暂时用UUID,终极方案是jwt
//            String key = "user:" + UUID.randomUUID();
            //存入redis(实行对象注入)
            loginUser.setPassword(null);
//使用jwt之后可以不用redis            redisTemplate.opsForValue().set(key,loginUser,30, TimeUnit.MINUTES);//登录30分钟限制

            //使用jwt
//            首先创建jwt
            String token = jwtUtil.createToken(loginUser);

            //返回数据到UserController
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            return data;
        }
        return null;
    }


    //登录
    @Override
    public Map<String, Object> getUserInfo(String token) {
        //根据token从redis中获取用户信息
//        Object obj = redisTemplate.opsForValue().get(token);
        User loginUser = null;
        try {
            loginUser = jwtUtil.parseToken(token,User.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //存进redis时是做了序列化处理，但是现在要拿出来，需要做一个反向的处理
        //判断obj是否从redis中取到
        if (loginUser != null) {
            //反序列化json
// 因为是从redis中取数据的，使用jwt后不需要           User loginUser = JSON.parseObject(JSON.toJSONString(obj), User.class);
            Map<String, Object> data = new HashMap<>();
            //名字
            data.put("name", loginUser.getUsername());
            //头像
            data.put("avatar", loginUser.getAvatar());
            //角色(较为复杂，需要使用关联查询出所有角色，因为一个人可能不止一个角色，在UserMapper.xml中做了查询)
            List<String> roleList = this.baseMapper.getRoleNameByUserId(loginUser.getId());
            data.put("roles", roleList);


            //权限列表（数据带给前端）
            List<Menu> menuList = menuService.getMenuListByUserId(loginUser.getId());
            data.put("menuList",menuList);
            return data;//返回数据到UserController
        }
        return null;
    }


    //在实现类中删掉token
    @Override
    public void logout(String token) {
//        不使用redis
//        redisTemplate.delete(token);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        //1、写入用户表
        this.baseMapper.insert(user);
        //2、写入角色用户表
        List<Integer> roleIdList = user.getRoleIdList();
        if(roleIdList != null){
            for(Integer roleId:roleIdList){
                userRoleMapper.insert(new UserRole(null, user.getId(),roleId));//null是因为前面的序号是自增的
            }
        }
    }

    @Override
    public User getUserById(Integer id) {
        //根据id查询数据
        User user = this.baseMapper.selectById(id);

        //查询角色列表数据
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoleList = userRoleMapper.selectList(wrapper);

        //只要roleIdList即可
        List<Integer> roleIdList = userRoleList.stream()
                .map(userRole -> {return userRole.getRoleId();})
                .collect(Collectors.toList());
//        List<String> roleList = this.baseMapper.getRoleNameByUserId(id);
//        user.setRoles(roleList.toString());
        user.setRoleIdList(roleIdList);
        return user;
    }

    @Override
    @Transactional
    public int updateUser(User user) {
        //更新用户表
        this.baseMapper.updateById(user);
        //user_role清除原有的角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(wrapper);
        //user_role做新增
        List<Integer> roleIdList = user.getRoleIdList();
        if(roleIdList != null){
            for(Integer roleId:roleIdList){
                userRoleMapper.insert(new UserRole(null, user.getId(),roleId));//null是因为前面的序号是自增的
            }
        }
        return 0;
    }


    @Override
    @Transactional
    public void deleteUserById(Integer id) {//非逻辑删除
        //删除用户表用户信息
        this.baseMapper.deleteById(id);
        //清除原有角色
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        userRoleMapper.delete(wrapper);
    }

    @Override
    public List<UserInfoVo> getUserInfoByIds(List<Integer> userIds) {
        return userMapper.selectBatchIds(userIds).stream()
                .map(UserInfoVo::fromUser)
                .collect(Collectors.toList());
    }

//    @Override
//    public void updatePassword(UserPasswordDTO userPasswordDTO) {
//        int update = UserMapper.updatePassword(userPasswordDTO);
//        if (update < 1) {
//            throw new ServiceException(Constants.CODE_600, "密码错误");
//        }
//    }

}
